<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline" v-if="permissionStore.hasPermisson('kwjts.cx')">
            <a-form-item label="客户" label-col-flex="80px">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                       v-model="pageData.customer" @press-enter="huiche"/>
            </a-form-item>
          </a-form>
        </div>
        <div class="my-tool-bar" style="float: right;">
          <Toolbar :items="pageData.btnList" @select="selectHandler" @add="addHandler" @del="deleteHandler"
          >
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18"/>
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18"/>
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999">
        <div style="width: 100%; height: 100%">
          <encapsulation-agrid ref="table1Ref" :configaggrid="configTable1"></encapsulation-agrid>
        </div>
      </a-spin>
    </template>
    <a-drawer :width="340" :visible="drawerVisible" @ok="handleDrawerOk" @cancel="handleDrawerCancel"
              @close="handleDrawerCancel" unmountOnClose>
      <template #title>
        {{ drawerData.title }}
      </template>
      <div>
        <a-form size="small" :model="drawerData" layout="inline" ref="drawerRef">
          <a-form-item label="客户" field="customer" label-col-flex="90px"
                       :rules="[{required:true,message:'客户必填'}]"
                       :validate-trigger="['blur']">

            <a-select popup-container="html" class="bacClass" v-model="drawerData.customer" @focus="getCustomers('')"
                      :style="{ width: '220px' }"
                      :loading="customerLoading"
                      @search="handleCustomerSearch" :filter-option="false" style="z-index: 1200" allow-search
                      allow-clear>
              <a-option v-for="(item, index) in drawerData.customerList" :key="index" :value="item['brandName']">
                {{ item['brandName'] }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="可完结条数" field="difference"
                       :rules="[{required:true,message:'可完结条数必填'}]"
                       :validate-trigger="['blur']"
                       label-col-flex="90px">
            <a-input-number :style="{ width: '200px' }" class="bacClass" placeholder="" :precision="0"
                            v-model="drawerData.difference" @press-enter="huiche"/>
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts" setup>
import {ref, reactive, onMounted, nextTick} from 'vue'
import usePermission from "@/store/modules/permission";
// import tableColumns from './tableConfig/CheckItem/table1'
import {post, get} from "@/api/http";
import {ElMessage} from "element-plus";
import {Message, Modal} from "@arco-design/web-vue";
import buttionRender from "@/components/aggridCellRenDerer/buttionRender.vue";

const customerLoading = ref<boolean>(false)
const fieldNames = {label: 'brandName', value: 'id'}
const handleCustomerSearch = (val: any) => {
  if (val) {
    customerLoading.value = true
    getCustomers(val)
    customerLoading.value = false
  }
}
const pageData = reactive({
  customer: '',//客户
  btnList: [],//按钮权限数组
  isEdit: false,//是否有修改权限
  pageLoading: false,//页面加载
})
const drawerData = reactive({
  title: '',
  id: '',//默认为空 只有修改时才有值
  customer: '',//客户
  customerList: [],//客户下拉框
  difference: '',//可完结条数
})
const drawerRef = ref<any>(null)
//设置权限
// ['查询', '新增', '删除', '导出', '导入']
const permissionStore = usePermission()

if (permissionStore.hasPermisson('kwjts.cx')) {
  pageData.btnList.push('查询')
}
if (permissionStore.hasPermisson('kwjts.xz')) {
  pageData.btnList.push('新增')
}
if (permissionStore.hasPermisson('kwjts.sc')) {
  pageData.btnList.push('删除')
}
if (permissionStore.hasPermisson('kwjts.xg')) {
  pageData.isEdit = true
}
const headerShow = ref<boolean>(true)
const drawerVisible = ref<boolean>(false)
const table1Ref = ref<any>(null)
const tableColumns = [
  {
    field: '',
    headerCheckboxSelection: true,
    checkboxSelection: true,
    width: 50,
    showDisabledCheckboxes: false,
    pinned: 'left',
  },
  {
    headerName: '客户',
    field: 'customer',
    width: 150,
  },
  {
    headerName: '完结条数',
    field: 'difference',
    width: 150,
  },
  {
    headerName: '创建人',
    field: 'createName',
    width: 150,
  },
  {
    headerName: '创建时间',
    field: 'createTime',
    width: 150,
  },
  {
    headerName: '最后修改人',
    field: 'updateName',
    width: 150,
  },
  {
    headerName: '最后修改时间',
    field: 'updateTime',
    width: 150,
  },
  {
    headerName: '操作',
    field: 'action',
    width: 150,
    filter: false,
    sortable: false,
    cellRenderer: buttionRender,
    cellRendererParams: {
      buttonList: [
        {
          type: 'primary',
          text: '修改',
          typeName: 'el-button',
          show: pageData.isEdit,
          Callback: (data: any) => {
            editHandler(data)
          },
        },
      ],
      eltagSize: 0,
    },
  }
]
let configTable1 = {
  url: 'planSingle/customerDifference/getPage', //接口路径
  queryData: {
    customer: pageData.customer,
    deleteState: 0
  },
  paginationShow: true, //分页是否显示
  invokeiIterface: true, //是否调用接
  rowMultiSelectWithClick: true, //点击行是否多选
  column: tableColumns,
  fileName: 'TerminalNum-1'
}
//查询渲染数据方法
const doRefresh = () => {
  table1Ref.value.setQuery({
    customer: pageData.customer,
    deleteState: 0
  })
}
//查询条件输入框回车触发的方法
const huiche = () => {
  doRefresh()
}
//点击查询按钮
const selectHandler = () => {
  doRefresh()
}
//获取客户下拉框
const getCustomers = async (val: any) => {
  const res = await post({
    url: 'product/Brand/getFieldValue',
    data: {
      brandName: val
    }
  })
  try {
    if (res.code == 200) {
      drawerData.customerList = res.data
    } else {
      ElMessage.error(res.message)
    }
  } catch (e) {
    console.log(e)
  }
}
const addHandler = async () => {
  drawerData.title = '新增'
  drawerVisible.value = true
}
const editHandler = async (data: any) => {
  const {customer, difference, id} = data
  drawerData.id = id
  drawerData.customer = customer
  drawerData.difference = difference
  drawerData.title = '修改'
  drawerVisible.value = true
}
const deleteHandler = () => {
  if (table1Ref.value.getSelectedRows().length == 0) {
    ElMessage.error('请选择要删除的数据')
    return
  }
  Modal.confirm({
    title: '系统提示',
    content: '确认删除选中的数据?',
    async onOk() {
      pageData.pageLoading = true
      const res = await post({
        url: 'planSingle/customerDifference/delete',
        data: table1Ref.value.getSelectedRows().map((item: any) => item.id)
      })
      try {
        if (res.code == 200) {
          ElMessage.success(res.message)
          doRefresh()
        } else {
          ElMessage.error(res.message)
        }
      } catch (e) {
        console.log(e)
      } finally {
        pageData.pageLoading = false
      }
    },
  })

}
const handleDrawerOk = async () => {
  const valid = await drawerRef.value.validate()
  if (!valid) {
    if (drawerData.title === '新增') {
      const res = await post({
        url: 'planSingle/customerDifference/insert',
        data: [{
          customer: drawerData.customer,
          difference: drawerData.difference
        }]
      })
      try {
        if (res.code == 200) {
          drawerVisible.value = false
          ElMessage.success(res.message)
          doRefresh()
        } else {
          ElMessage.error(res.message)
        }
      } catch (e) {
        console.log(e)
      }
    } else if (drawerData.title === '修改') {
      const res = await post({
        url: 'planSingle/customerDifference/update',
        data: [
          {
            id: drawerData.id,
            customer: drawerData.customer,
            difference: drawerData.difference
          }
        ]
      })
      try {
        if (res.code == 200) {
          drawerVisible.value = false
          ElMessage.success(res.message)
          doRefresh()
        } else {
          ElMessage.error(res.message)
        }
      } catch (e) {
        console.log(e)
      }
    }

  }
}
const handleDrawerCancel = () => {
  drawerVisible.value = false
  for (let k in drawerData) {
    drawerData[k] = ''
  }
}
</script>
<style scoped>
.arco-input-wrapper.arco-input-disabled {
  border: 1px solid #a29f9f !important;
}

.form {
  width: 100vw !important;
}
</style>
